package com.bort.system.security;

import com.bort.system.model.Menu;
import com.bort.system.model.User;
import com.bort.system.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class AdminShiroRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;


    //  权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User user = (User)principalCollection.getPrimaryPrincipal();

        List<String> perms = new ArrayList<>();

        // 获取用户权限

        List<Menu> actions =  userService.getUserAuthorizedMenus(user.getId());

        if(actions != null){
            for(Menu action:actions){
                perms.add(action.getActionCode());
            }
        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }

    // 登录/授权
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        SimpleAuthenticationInfo info = null;
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String account = token.getUsername();
        User user = userService.findByUserName(account);

        if(null == user){
            throw new UnknownAccountException();
        }else if(user.getType() != 1) {
            throw new DisabledAccountException();
        }else if(user.getStatus() != 1){
            throw new LockedAccountException();
        } else{
//            ByteSource credentialsSalt = ByteSource.Util.bytes(account+"salt");
//            info = new SimpleAuthenticationInfo(user,user.getPassword(),credentialsSalt,"shiroRealm");
            info = new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
        return info;
    }



    @Override
    public void onLogout(PrincipalCollection principals) {
        System.out.println("");
        super.onLogout(principals);
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

}
